package cn.itzzx.lagou.netty.rpc.common.util;

import cn.itzzx.lagou.netty.rpc.common.service.UserService;
import org.apache.curator.framework.CuratorFramework;

import java.util.*;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
public class ServerLoadBalancerUtil {


    public static UserService selectBalanceService(Map<String, UserService> servers, CuratorFramework client) throws Exception {
        Set<String> strings = servers.keySet();
        Map<Long, String> banlance = new HashMap<>();
        for (String string : strings) {
            String delay = new String((client.getData().forPath("/delay/" + string)), "UTF-8");
            Long var = 0L;
            //如果发现延迟相同，后面的服务器延迟时间+1
            if (banlance.containsKey(delay)) {
                var = Long.parseLong(delay) + 1;
            } else {
                var = Long.parseLong(delay);
            }
            banlance.put(var, string);
        }
        Iterator<Map.Entry<Long, String>> iterator = banlance.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, String> next = iterator.next();
            System.out.print("服务器: " + next.getValue().split("&")[0] + "的延迟为:" + next.getKey() +"\t");
        }

        Set<Long> longs = banlance.keySet();
        Long min = Collections.min(longs);
        //选择延迟最小的
        String serviceId = banlance.get(min);
        System.out.println(">>>>>>>>>选择性能最佳服务器: " + serviceId.split("&")[0]);
        UserService userService = servers.get(serviceId);
        return userService;
    }

}
